package es.upv.epsa.mobweb.moneyback.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.util.Log;
 
public class JSONParser {
 
    static InputStream 	is 		= null;
    static JSONObject 	jObj 	= null;
    static String 		json 	= "";
 
    public JSONParser() {
 
    }
 
    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
 
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient 	httpClient 		= new DefaultHttpClient();
            HttpPost 			httpPost 		= new HttpPost(url);
            
            httpPost.setEntity(new UrlEncodedFormEntity(params));
 
            HttpResponse 		httpResponse 	= httpClient.execute(httpPost);
            HttpEntity 			httpEntity 		= httpResponse.getEntity();
            
            is = httpEntity.getContent();           
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        try {
            BufferedReader 	reader 	= new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder 	sb 		= new StringBuilder();
            String 			line 	= null;
            
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
 
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
 
        // return JSON String
        return jObj;
    }
    
    public String sendJSON(String serverUrl, String json){
    	String data 			= null;
    	int TIMEOUT_MILLISEC 	= 10000;
    	HttpParams httpParams 	= new BasicHttpParams();
    	
    	HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
    	HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
    	
    	HttpClient client 		= new DefaultHttpClient(httpParams);
    	HttpPost request 		= new HttpPost(serverUrl);
    	request.addHeader("Content-Type", "application/json");
    	
    	try {
			request.setEntity(new ByteArrayEntity(json.getBytes("UTF8")));
			HttpResponse response = client.execute(request);
			
			HttpEntity entity = response.getEntity();
	        if(entity != null) {
	            InputStream instream = entity.getContent();
	            data = JSONParser.convertStreamToString(instream);
	        }
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
    	return data;
    }
    
    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}